//
//  HMSqliteManager.swift
//  WeiBo
//
//  Created by Feng on 2017/6/18.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import FMDB

//数据库路径
let DBPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("WeiBo.db")

class HMSqliteManager: FMDatabaseQueue {

    //单例全局访问点
    static let sharedManager: HMSqliteManager =
    {
        let sqliteManager = HMSqliteManager(path: DBPath)
        
        sqliteManager?.createTable()
        
        return sqliteManager!
    }()
    
    //创建表
    private func createTable()
    {
        //文件路径
        let sqlPath = Bundle.main.path(forResource: "db.sql", ofType: nil)!
        let sql = try! String(contentsOfFile: sqlPath)
        
        self.inDatabase { (db) in
            let isOK = db?.executeStatements(sql)
            
            if isOK == true
            {
                print("建表成功")
                print(DBPath)
            }
            else
            {
                print("建表失败")
            }
        }
    }
 
    //  根据sql语句查询返回字典数组
    func selectDictArray(sql: String) -> [[String: Any]]
    {
        var tempArray = [[String: Any]]()
        
        self.inDatabase { (db) in
            if let resultSet = db?.executeQuery(sql, withArgumentsIn: [])
            {
                while resultSet.next()
                {
                    var dic = [String: Any]()
                    
                    let colCount = resultSet.columnCount()
                    
                    for i in 0..<colCount
                    {
                        let colName = resultSet.columnName(for: i)!
                        let colValue = resultSet.object(forColumnIndex: i)!
                        dic[colName] = colValue
                    }
                    tempArray.append(dic)
                }
                
            }
        }
        return tempArray
    }
    
}
